//
// Created by ftd on 2021/8/19.
// 锁的扩展类
//

#ifndef DEMO_MUTEX_EXT_H
#define DEMO_MUTEX_EXT_H
#include <thread>

class SpinLock {
public:
    SpinLock(std::atomic_flag& flag, int spin_count) : flag_(flag) {
        for (;;) {
            if (!flag_.test_and_set(std::memory_order_acquire)) {
                return;
            }

            for (int n = 1; n < spin_count; n <<= 1) {
                for (int i = 0; i < n; ++i) {
                    __asm__ __volatile__("pause;");
                }
                if (!flag_.test_and_set(std::memory_order_acquire)) {
                    return;
                }
            }
            std::this_thread::yield();
        }
    }
    SpinLock(std::atomic_flag& flag) : flag_(flag) {
        while (flag_.test_and_set(std::memory_order_acquire)) {
            //std::this_thread::yield();
        }
    }
    ~SpinLock() {
        flag_.clear(std::memory_order_release);
    }

    SpinLock(const SpinLock&) = delete;
    SpinLock& operator= (const SpinLock&) = delete;
private:
    std::atomic_flag& flag_;
};
#endif //DEMO_MUTEX_EXT_H
